#-*- coding:utf8 -*-
import config
import time
from app.base import BaseHandler
import htmlentitydefs
import re
from lib.session import Session
from tornado.web import authenticated

class QuestionHandler(BaseHandler):
    
    def initialize(self, method = ''):
        self.__method = method
        
    @authenticated
    def get(self, args = ''):
        if self.__method == 'questions':
            self.__questions_show()
        else:
            if args == '':
                self.display('question.html')
            elif args == '/following':
                self.__following_show()
            elif args == '/invited':
                self.__invited_show()
            elif args == '/about':
                self.__about_show()
            elif args == '/recommend':
                self.__recommend_show()
            elif args == '/topic_edit':
                self.__show_topic_edit()
            else:
                args = args[1:]
                self.__show(args)
    
    @authenticated
    def post(self, args = ''):
        if args == '/unbind':
            self.__unbind()
        if args == '/bind':
            self.__bind()
        if args == '/update_title':
            self.__update_title()
        if args == '/update_detail':
            self.__update_detail()
        if args == '/follow':
            self.__follow()
        else:
            self.__add_question()
    
    def __add_question(self):
        title = self.get_argument('title', '')
        detail = self.get_argument('detail', '')
        topic = self.get_argument('topic', '')
        topic_list = topic.split(',')
        if len(topic_list) == 0:
            self.write(u'请输入话题')
        elif len(title) == 0:
            self.write(u'请输入标题')
        else:
            conn = config.getDBConnect()
            topic_ids = self.__update_topic(conn, topic_list)
            if len(topic_ids) > 0:
                topic_str = ','.join(topic_ids)
                s = Session(self)
                uid = s.get('uid')
                if uid == None:
                    uid = 0
                sql = "INSERT INTO `question` (`id_user`,`title`,`topic`,`detail`,`tm_add`) VALUE (%d, '%s', '%s', '%s', %d)" % (uid, title, topic_str, detail, time.time())
                try:
                    if conn.execute(sql):
                        sql = "UPDATE `topic` SET `nr_question` = `nr_question` + 1 WHERE `id` in (%s)" % topic_str
                        conn.execute(sql)
                    self.write(u'添加成功')
                    self.redirect('/')
                except:
                    self.write(u'执行出错')
            else:
                self.write(u'话题更新失败')

    
    def __show_topic_edit(self):
        question_id = self.get_argument('id', 0)
        conn = config.getDBConnect()
        sql = "SELECT a.topic from `question` a  where a.`id`=%d" %(int(question_id))
        try:
            row = conn.get(sql)
            row['topic'] = self.__topic_query(conn, row.topic)
            self.display('question_topic_edit.html', topics=row.topic)
        except:
            self.write("question_topic_edit error")
        
    def __show(self, args):
        conn = config.getDBConnect()
        s = Session(self)
        uid = int(s.get('uid'))
        try:
            question = self.__question_query(conn, args)
            if not question:
                return self.write("question not exist!")
            
            items = self.__relevance_question_query(conn)
            sql = "SELECT a.`id` AS aid, a.`content`, a.`tm_add`, a.`cnt_agree`, "\
                "b.`id` AS uid, b.`name`, b.`signature`, IFNULL(c.`status`, 0) as `status`, "\
                "IFNULL(d.`status`, 0) as `thank`, IFNULL(e.`status`, 0) as `nohelp` "\
                "FROM `answer` AS a LEFT JOIN `user` AS b ON a.`id_user` = b.`id` "\
                "LEFT JOIN answer_vote as c on a.id = c.id_answer and c.id_user=%d "\
                "LEFT JOIN answer_attr as d on a.id = d.id_answer and d.id_user=%d and d.type = 0 "\
                "LEFT JOIN answer_attr as e on a.id = e.id_answer and e.id_user=%d and e.type = 1 "\
                "WHERE a.`id_question` = %d" %(uid, uid, uid, int(args))
            answer = conn.query(sql)
            if answer == None:
                answer = []
            else:
                pattern = re.compile("&(\w+?);")
                i = 0
                while i < len(answer):
                    answer[i].content = pattern.sub(self.__html_decode, answer[i].content)
                    answer[i].tm_add = config.time_from_now(int(answer[i].tm_add))
                    answer[i]['votes'] = self.__query_answer_vote(conn, answer[i].aid)
                    i += 1
                    
            self.display('question_detail.html', user=s, question=question, items=items, answers=answer)
        except:
            print sys.exc_info()[0],sys.exc_info()[1]
            self.write('error!')
            return
    
    def __query_answer_vote(self, conn, aid):
        sql = "SELECT a.`id_user`, b.`name` FROM `answer_vote` a, `user` b "\
                "WHERE a.`id_answer`=%d and a.`status` = 1 and a.`id_user` = b.`id` limit 3"%(aid)
        try:
            rows = conn.query(sql)
            return rows
        except:
            return []
        
        
    def __html_decode(self, m):
        return htmlentitydefs.entitydefs[m.group(1)]
    
    
        
    def __update_topic(self, conn, topic_list):
        re = []
        for topic in topic_list:
            sql = "SELECT `id` FROM `topic` WHERE `name` = '%s'" % topic
            try:
                row = conn.get(sql)
                if not row:
                    sql = "INSERT INTO `topic` (`name`, `add_time`) VALUE ('%s', %d)" % (topic, time.time())
                    id = conn.execute_lastrowid(sql)
                    if id > 0:
                        re.append(str(id))
                else:
                    re.append(str(row['id']))
            except:
                pass
        return re
    
    def __question_query(self, conn, id):
        s = Session(self)
        uid = int(s.get('uid'))
        sql = "SELECT a.`id`, a.`title`, a.`detail`, a.`cnt_comment`,a.`cnt_answer`, "\
            "a.`cnt_follow`, a.`cnt_view`, a.`topic`, IFNULL(b.`status`, -1) as `follow` "\
            "from `question` a LEFT JOIN `question_fans` b ON a.`id`=b.`id_question` "\
            "and b.`id_user`=%d where a.`id`='%s' " %(uid, id)
        try:
            row = conn.get(sql)
            row['topic'] = self.__topic_query(conn, row.topic)
            return row
        except:
            return None
        
    def __relevance_question_query(self, conn):
        sql = "SELECT `id`, `title` from `question` limit 5"
        try:
            rows = conn.query(sql)
            if not rows:
                return[]
            else:
                return rows
        except:
            return []
    
    def __questions_show(self):
        s = Session(self)
        conn = config.getDBConnect()
        sql = "SELECT a.`id`, a.`title`, a.`detail`, a.`tm_add`, "\
            "b.`name` as user_name from `question` a , `user` b "\
            "where a.id_user = b.id"
        try:
            rows = conn.query(sql)
            for row in rows:
                row.tm_add = config.time_from_now(int(row.tm_add))
        except:
            rows=[]
        self.display('questions.html', user=s, res=[], questions=rows)
    
    def __invited_show(self):
        s=Session(self)
        conn = config.getDBConnect()
        about_cnt = dict(invited=10, about=20)
        sql = "SELECT a.`id`, a.`title`, b.name as user_name "\
            "from `question` a, user b where a.id_user = b.id "
        try:
            rows = conn.query(sql)
        except:
            rows = []
        self.display('invited.html', user=s, res=[], about_cnt=about_cnt, questions=rows)
        
        
    def __about_show(self):
        s=Session(self)
        conn = config.getDBConnect()
        about_cnt = dict(invited=10, about=20)
        sql = "SELECT a.`id`, a.`title`, b.name as user_name "\
            "from `question` a, user b where a.id_user = b.id "
        try:
            rows = conn.query(sql)
        except:
            rows = []
        self.display('about.html', user=s, res=[], about_cnt=about_cnt, questions=rows)
        
    def __recommend_show(self):
        s=Session(self)
        conn = config.getDBConnect()
        about_cnt = dict(invited=10, about=20)
        
        sql = "SELECT a.`id`, a.`title`, a.topic "\
            "from `question` a"
        try:
            rows = conn.query(sql)
            for row in rows:
                topic = self.__topic_query(conn, row.topic)
                row['topic'] = topic
        except:
            rows = []
        self.display('recommend.html', user=s, res=[], about_cnt=about_cnt, questions=rows)
        
    
    def __following_show(self):
        s = Session(self)
        conn = config.getDBConnect()
        sql = "SELECT a.`id`, a.`title`, a.`tm_add`, a.`cnt_answer`, "\
            "a.topic from `question` a  "
        try:
            rows = conn.query(sql)
            for row in rows:
                topic = self.__topic_query(conn, row.topic)
                row['topic'] = topic
        except:
            rows=[]
        self.display('following.html', user=s, res=[], questions=rows)
    
    def __topic_query(self, conn, topic):
        rtn = []
        topics = topic.split(',')
        try:
            for item in topics:
                sql = "SELECT `id`, `name`, `description`, `nr_question`, `add_time`" \
                    "FROM `topic` WHERE id = %d " %(int(item))
                row = conn.get(sql)
                rtn.append(row)
        finally:
            return rtn
    
    def __unbind(self):
        question_id = int(self.get_argument('question_id', ''))
        topic_id = self.get_argument('topic_id', '')
        conn = config.getDBConnect()
        sql = "SELECT `topic` FROM `question` WHERE `id`=%d"%(question_id)
        try:
            row = conn.get(sql)
            topics = row.topic.split(',')
            topics.remove(topic_id)
            str = ",".join(topics)
            sql = "UPDATE `question` SET `topic` = '%s' where `id`=%d"%(str, question_id)
            conn.execute(sql)
            self.write("__unbind success")
        except:
            self.write("__unbind failed")
    
    def __bind(self):
        question_id = int(self.get_argument('question_id', ''))
        topic_name = self.get_argument('topic_id', '')
        conn = config.getDBConnect()
        topic_list=topic_name.split(',')
        try:
            topic_ids = self.__update_topic(conn, topic_list)
            topic_id = ','.join(topic_ids)
       
            sql = "SELECT `topic` FROM `question` WHERE `id`=%d"%(question_id)
            row = conn.get(sql)
            topic_list = []
            if row.topic <> "":
                topic_list = row.topic.split(',')
            try:
                topic_list.index(topic_id)
            except:
                topic_list.append(topic_id)
                topic_str = ",".join(topic_list)
                sql = "UPDATE `question` SET `topic` = '%s' where `id`=%d"%(topic_str, question_id)
                conn.execute(sql)
                topic={'name':topic_name, 'id':topic_id}
                self.display('question_topic_edit_item.html', topic=topic)
        except:
            self.write("__bind failed")
    
    def __update_title(self):
        question_id = int(self.get_argument('question_id', ''))
        title = self.get_argument('title', '')
        conn = config.getDBConnect()
        sql = "UPDATE `question` SET `title` = '%s' where `id`=%d"%(title, question_id)
        try:
            conn.execute(sql)
            self.write("__update_title success")
        except:
            self.write("__update_title failed")
            
    def __update_detail(self):
        question_id = int(self.get_argument('question_id', ''))
        detail = self.get_argument('detail', '')
        conn = config.getDBConnect()
        sql = "UPDATE `question` SET `detail` = '%s' where `id`=%d"%(detail, question_id)
        try:
            conn.execute(sql)
            self.write("__update_title success")
        except:
            self.write("__update_title failed")
            
    def __follow(self):
        qid = int(self.get_argument('question_id', ''))
        status = int(self.get_argument('status', ''))
        s = Session(self)
        uid = s.get('uid')
        conn = config.getDBConnect()
        sql = "SELECT `status` FROM `question_fans` WHERE `id_question`=%d"\
            " and `id_user`=%d"%(qid, uid)
        old_status = -1
        try:
            row = conn.get(sql)
            if row <> None:
                old_status = row.status
                
            if old_status <> status:
                if (row <> None):
                    sql = "UPDATE `question_fans` SET `status`=%d where `id_question`=%d"\
                        " and `id_user`=%d"%(status, qid, uid)
                else:
                    sql = "INSERT INTO `question_fans` (`id_question`, `id_user`, `status`, `add_time`) "\
                        "VALUES (%d, %d, %d, %d)" %(qid, uid, status, time.time())
                conn.execute(sql)
                sql = "UPDATE `question` SET `cnt_follow` = `cnt_follow` + %d "\
                "where `id`=%d" %(status, qid)
                conn.execute(sql)
            
            self.write("__follow success")
        except:
            self.write("__follow failed")
                